package com.m3958.firstgwt.server.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.fileupload.ProgressListener;

import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;

public class UploadProgressListener implements ProgressListener{

	private long pBytesRead;
	private long pContentLength;
	private int itemIndex;
	
	private List<String> fnames = new ArrayList<String>();
	
	private Date createdAt;
	
	private String submitId;
	
	@Inject
	private UploadProgressKeeper keeper;
	
	@Inject
	public UploadProgressListener(@Assisted String submitId){
		this.submitId = submitId;
		createdAt = new Date();
	}
	

	
//	pBytesRead - The total number of bytes, which have been read so far.
//	pContentLength - The total number of bytes, which are being read. May be -1, if this number is unknown.
//	pItems - The number of the field, which is currently being read. (0 = no item so far, 1 = first item is being read, ...)
//它监听的是整个formsubmit，pContentLength是整个form的长度，pBytes是当前已读长度，	
	@Override
	public void update(long pBytesRead, long pContentLength, int itemIndex) {
		this.pBytesRead = pBytesRead;
		this.pContentLength = pContentLength;
		this.itemIndex = itemIndex;
		if(pBytesRead >= pContentLength){
			keeper.removeListener(submitId);
		}
	}
	
	public String toJsonString(){
		JSONObject jo = new JSONObject();
		jo.element("readedBytes", pBytesRead);
		jo.element("totalBytes", pContentLength);
		jo.element("currentIndex", itemIndex);
		jo.element("fileNames", JSONArray.fromObject(fnames));
		return jo.toString();
	}

	public List<String> getFnames() {
		return fnames;
	}

	public void addFnames(String fname) {
		this.fnames.add(fname);
	}

	public Date getCreatedAt() {
		return createdAt;
	}
	

}
